#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   user.py
@Time    :   2024/01/02 15:31:57
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import os
import base64
from io import BytesIO 
from PIL import Image  
from ninja import Router,File, UploadedFile
from django.shortcuts import get_object_or_404
from django.forms import model_to_dict
from typing import Union
from django.core.files.base import ContentFile


from big_event import settings
from utils.response import R
from utils.auth import get_user_info_from_token
from system.schema import UserInfo,PassWordSchemaIn,UpdateUserInfo,AvatarSchema
from system.models import Users
from utils.tools import image_to_base64

router = Router()

@router.get("/userinfo",summary="用户信息",response=Union[UserInfo, R])
def get_user_info(request):
    try:
        user_info = get_user_info_from_token(request)
        user = get_object_or_404(Users, id=user_info['id'])
        data = UserInfo(**model_to_dict(user))
        return R.ok(data=data,msg='认证成功')
    except Exception as e:
        return R.fail(msg="身份认证失败")

    
    
@router.put("/userinfo", summary="更新用户信息",response=Union[UserInfo, R])
def update_user_info(request, data: UpdateUserInfo):
    # 从请求中获取用户信息
    request_user = get_user_info_from_token(request)
    request_user_id = request_user['id']
    if data.id!= request_user_id:
        return R.fail(msg="用户id不匹配")
    user_obj = get_object_or_404(Users, id=data.id)
    try:
        # 更新用户信息
        dict_data = data.dict()
        for attr, value in dict_data.items():
            setattr(user_obj, attr, value)
        user_obj.save()
        # 将更新后的用户信息转换为字典形式
        data = UserInfo(**model_to_dict(user_obj))
        return R.ok(data=data, msg='修改用户信息成功')
    except Exception as e:
        return R.fail(msg="修改用户信息失败")
    
    
    
@router.post("/updatepwd", summary="更新密码",response=Union[UserInfo, R])
def repassword(request, data: PassWordSchemaIn):
    # 从请求中获取用户信息
    request_user = get_user_info_from_token(request)
    request_user_id = request_user['id']
    # 验证两次密码是否一致
    if data.new_pwd != data.re_pwd:
        return R.fail(msg="两次密码不一致")
    # 验证用户和密码是否正确
    user_obj = get_object_or_404(Users, id=request_user_id)
    if user_obj is None:
        return R.fail(msg="用户不存在")
    # 检查输入的旧密码是否匹配
    if user_obj.check_password(data.old_pwd):
        user_obj.set_password(data.new_pwd)
        user_obj.save()
        # 将更新后的用户信息转换为字典形式
        data = UserInfo(**model_to_dict(user_obj))
        return R.ok(data=data, msg='更新密码成功')
    else:
        return R.fail(msg="原密码错误")
        

@router.put("/resetpwd/{id}",summary="重置密码", response=R)
def reset_password(request, id:int):
    request_user = get_user_info_from_token(request)
    # 判断是否为超级管理员
    if request_user.get('is_superuser', False):
        user_obj = get_object_or_404(Users, id=id)
        user_obj.set_password('123456')
        user_obj.save()
        return R.ok(msg='密码重置成功')
    else:
        return R.fail(msg='权限不足')
    
    
# 通过上传的base64图片进行头像的上传
@router.post("/update/avatar", summary="上传base64头像",response=R)
def update_user_pic_base64(request, data:AvatarSchema):
    request_user = get_user_info_from_token(request)
    user_obj = get_object_or_404(Users, id=request_user['id'])
    try:
        # 获取上传的 Base64 图片数据  
        base64_data =  data.avatar
        # 解码 Base64 图片数据并转换为字节流
        header,content = base64_data.split(",")
        image_data = base64.b64decode(content)
        # 检查图片是否为空
        if not image_data:
            return R.fail(msg="图片数据为空")
        # 添加convert('RGB')解决保存图片前的预处理问题
        image = Image.open(BytesIO(image_data)).convert('RGB')
        # 调整图片大小  
        image = image.resize((80, 80))
        # 保存头像的路径
        image_name =  f"{user_obj.username}_avatar.png"
        # 将字节流保存为文件  
        image_file = ContentFile(image_data, name=image_name)
        # 保存头像到数据库和文件系统
        user_obj.user_pic = image_file
        user_obj.save()
        return R.ok(data={"url": user_obj.user_pic.url},msg="上传头像成功")
    except Exception as e:
        return R.fail(msg="上传头像失败")   


@router.post("/update/pic", summary="上传头像")
def update_user_pic(request, avatar: UploadedFile = File(...)):
    # 从请求中获取用户信息
    request_user = get_user_info_from_token(request)
    # 头像保存路径
    root = os.path.join(settings.MEDIA_ROOT, "avatars")
    image_name = f"{request_user['username']}_avatar.png"
    if not os.path.isdir(root):
        os.mkdir(root)
    avatar_file = os.path.join(root, image_name)
    try:
        with open(avatar_file, "wb") as w:
            w.write(avatar.read())
        # 获取用户对象
        user_obj = get_object_or_404(Users, id=request_user['id'])
        # 设置用户头像URL
        user_obj.user_pic = f"avatars/{image_name}"
        user_obj.save()
        return R.ok(data={"url": user_obj.user_pic.url},msg="上传头像成功")
    except Exception as e:
        return R.fail(msg="上传头像失败")

    


    
    